package io.gitee.thinkbungee.factory;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import io.gitee.thinkbungee.config.MongoCondition;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author chenyichang
 * @date 2022/3/8
 */
@Component
@Conditional(MongoCondition.class)
public class MongoDBCollectionFactory {

    private static final String TABLE_NAME = "tableName";

    private static MongoDatabase mongoDatabase;

    @Autowired
    private MongoDatabase database;

    @PostConstruct
    public void initMongoDatabase() {
        mongoDatabase = database;
    }

    /**
     * 获取该mongo库的表数量
     *
     * @param map 查询条件
     * @return
     */
    public static int getCollectionTotal(Map<String, Object> map) {
        if (map.containsKey(TABLE_NAME)) {
            return getCollectionNames(String.valueOf(map.get(TABLE_NAME))).size();
        }
        return getCollectionNames().size();
    }

    /**
     * 通过表名获得查询对象
     *
     * @param collectionName 表名
     * @return 查询对象
     */
    public MongoCollection<Document> getCollection(String collectionName) {
        return mongoDatabase.getCollection(collectionName);
    }

    /**
     * 获得当前数据库的所有的集合名字
     *
     * @param map 查询条件（和关系型数据库一致）
     * @return 集合名字
     */
    public static List<String> getCollectionNames(Map<String, Object> map) {
        int limit = Integer.parseInt(map.get("limit").toString());
        int skip = Integer.parseInt(map.get("offset").toString());
        List<String> names;
        if (map.containsKey(TABLE_NAME)) {
            names = getCollectionNames(map.get(TABLE_NAME).toString());
        } else {
            names = getCollectionNames();
        }
        return names.stream().skip(skip).limit(limit).collect(Collectors.toList());
    }

    /**
     * 获取名字包含tableName的集合
     *
     * @param tableName
     * @return
     */
    private static List<String> getCollectionNames(String tableName) {
        return getCollectionNames().stream().filter(name -> name.contains(tableName)).collect(Collectors.toList());
    }

    /**
     * 获取所有集合名
     */
    private static List<String> getCollectionNames() {
        MongoIterable<String> tableNames = mongoDatabase.listCollectionNames();
        List<String> result = new ArrayList<>();
        for (String name : tableNames) {
            result.add(name);
        }
        return result;
    }

}
